package com.meitianhui.convenitenbuy.module.home.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.module.home.adapter.HomeEdinburghGoodsAdapter;
import com.meitianhui.convenitenbuy.module.home.adapter.HomeHistorySearchAdapter;
import com.meitianhui.convenitenbuy.module.home.contract.HomeSearchContract;
import com.meitianhui.convenitenbuy.module.home.di.DaggerHomeComponent;
import com.meitianhui.convenitenbuy.module.home.di.HomeModule;
import com.meitianhui.convenitenbuy.module.home.model.bean.HomeGoodsInfo;
import com.meitianhui.convenitenbuy.module.home.model.database.SearchHistoryDataBean;
import com.meitianhui.convenitenbuy.module.home.model.database.SearchHistoryDataBeanDao;
import com.meitianhui.convenitenbuy.module.home.presenter.HomeSearchPresenter;
import com.meitianhui.convenitenbuy.module.home.ui.activity.web.EdinburghWebViewActivity;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;

import java.util.List;

import javax.inject.Inject;

/**
 * Created by Administrator on 2017/11/15.
 */

public class HomeSearchActivity extends BaseActivity implements HomeSearchContract.View {
    private RecyclerView mRvHomeSearch;
    private EditText mEtSearch;
    private HomeEdinburghGoodsAdapter mAdapter;
    private HomeHistorySearchAdapter mHistoryAdapter;
    private int mPageIndex = 1;
    private int mPageSize = 15;
    private String mSearch = "";
    private View mNotDataView;
    private List<HomeGoodsInfo.Convient> homeGoodsInfo;
    @Inject
    HomeSearchPresenter presenter;
    private boolean currentAdapterType = false;
    private SearchHistoryDataBeanDao mDao;
    private List<SearchHistoryDataBean> mHistoryList;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_home_search);
        DaggerHomeComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
        mDao = App.getInstance().getDaoSession().getSearchHistoryDataBeanDao();
        initView();
        initInfo();
    }

    /**
     * 获取用户历史搜索记录
     */
    private void initInfo() {
        mHistoryList = findAllHistorySearch();
            mHistoryAdapter = new HomeHistorySearchAdapter(this, mHistoryList);
            mRvHomeSearch.setAdapter(mHistoryAdapter);
            mHistoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    if (adapter.getItemViewType(position) == BaseQuickAdapter.FOOTER_VIEW) {
                        clearHistorySearch();
                    }
                    SearchHistoryDataBean item = (SearchHistoryDataBean) adapter.getItem(position);
                    mPageIndex = 1;
                    if(item!=null){
                        String history = item.getHistory();
                        presenter.searchGoods(mPageIndex + "", mPageSize + "", history);
                        currentAdapterType = true;
                        mRvHomeSearch.setAdapter(mAdapter);
                        mEtSearch.setText(history);
                        mEtSearch.setSelection(history.length());
                        SystemUtils.hidKeyBoard(HomeSearchActivity.this);
                        item.setSearchTime(System.currentTimeMillis());
                        mDao.update(item);
                    }
                }
            });
    }

    private void clearHistorySearch() {
        mDao.deleteAll();
    }


    private void initView() {
        mRvHomeSearch = getViewById(R.id.rv_home_search);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvHomeSearch.setLayoutManager(linearLayoutManager);
        RxUtils.bindEvents(getViewById(R.id.tv_cancel), this);
        mEtSearch = getViewById(R.id.et_search);
        mNotDataView = getLayoutInflater().inflate(R.layout.data_empty_goods, (ViewGroup) mRvHomeSearch.getParent(), false);
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!currentAdapterType) {
                    mRvHomeSearch.setAdapter(mAdapter);
                    currentAdapterType = true;
                }
                if (!TextUtils.isEmpty(s.toString().trim())) {
                    mPageIndex = 1;
                    mSearch = s.toString();
                    presenter.searchGoods(mPageIndex + "", mPageSize + "", mSearch);
                } else {
                    mRvHomeSearch.setAdapter(mHistoryAdapter);
                    currentAdapterType = false;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mAdapter = new HomeEdinburghGoodsAdapter(HomeSearchActivity.this, null);

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPageIndex++;
                presenter.searchGoods(mPageIndex + "", mPageSize + "", mSearch);
            }
        }, mRvHomeSearch);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String goodId = homeGoodsInfo.get(position).getGoods_id();
                String data_source = homeGoodsInfo.get(position).getData_source();
    /*            //进入领了么详情
                Intent intent = new Intent(HomeSearchActivity.this, EdinburghWebViewActivity.class);
                if (InfoProvider.getLoginStatus(HomeSearchActivity.this)) {
                    intent.putExtra("url", Constants.HOST + "h5/c/payback/detail?goods_id="
                            + goodsId + "&mi=" + InfoProvider.getUserToken(App.getInstance()).getMember_id() + "&mobile=" + InfoProvider.getUserToken(App.getInstance()).getMobile() + "&bind=1");
                } else {
                    intent.putExtra("url", Constants.HOST + "h5/c/payback/detail?goods_id="
                            + goodsId + "&bind=1");
                }
                intent.putExtra("title", "淘淘领");
                intent.putExtra("is_second", true);
                startActivity(intent);*/

                if ("huiguo".equals(data_source)){
                    //跳转到会过的商品详情界面
                    Intent intent = new Intent(HomeSearchActivity.this, EdinburghWebViewActivity.class);
                    if (InfoProvider.getLoginStatus(HomeSearchActivity.this)) {
                        intent.putExtra("url", Constants.HOST + "h5/c/payback/huiguo-detail?goods_id="
                                + goodId  + "&mi=" + InfoProvider.getUserToken(App.getInstance()).getMember_id()+ "&mobile=" + InfoProvider.getUserToken(App.getInstance()).getMobile() );
                    } else {
                        intent.putExtra("url", Constants.HOST + "h5/c/payback/huiguo-detail?goods_id="
                                + goodId );
                    }
                    intent.putExtra("title", "会过");
                    intent.putExtra("is_second", true);
                   startActivity(intent);

                }else if(  "meitianhui".equals(data_source)) {
                    //跳转到自营商品的界面
                    Intent intent = new Intent(HomeSearchActivity.this, EdinburghWebViewActivity.class);
                    if (InfoProvider.getLoginStatus(HomeSearchActivity.this)) {
                        intent.putExtra("url", Constants.HOST + "h5/c/payback/ziying-detail?goods_id="
                                + goodId  + "&mi=" + InfoProvider.getUserToken(App.getInstance()).getMember_id()+ "&mobile=" + InfoProvider.getUserToken(App.getInstance()).getMobile() );
                    } else {
                        intent.putExtra("url", Constants.HOST + "h5/c/payback/ziying-detail?goods_id="
                                + goodId );
                    }
                    intent.putExtra("title", "自营");
                    intent.putExtra("is_second", true);
                    startActivity(intent);

                }else {
                    Intent intent = new Intent(HomeSearchActivity.this, EdinburghWebViewActivity.class);
                    if (InfoProvider.getLoginStatus(HomeSearchActivity.this)) {
                        intent.putExtra("url", Constants.HOST + "h5/c/payback/detail?goods_id="
                                + goodId + "&mi=" + InfoProvider.getUserToken(App.getInstance()).getMember_id() + "&mobile=" + InfoProvider.getUserToken(App.getInstance()).getMobile() + "&bind=1");
                    } else {
                        intent.putExtra("url", Constants.HOST + "h5/c/payback/detail?goods_id="
                                + goodId + "&bind=1");
                    }
                    intent.putExtra("title", "淘淘领");
                    intent.putExtra("is_second", true);
                    startActivity(intent);
                }
                saveSearchIntoHistory(mEtSearch.getText().toString().trim());
            }


        });

    }

    private void saveSearchIntoHistory(String search) {
        SearchHistoryDataBean bean = new SearchHistoryDataBean();
        bean.setSearchTime(System.currentTimeMillis());
        bean.setHistory(search);
        mDao.insertOrReplace(bean);
        mHistoryList = findAllHistorySearch();
        mHistoryAdapter.replaceData(mHistoryList);
        mHistoryAdapter.addHeaderAndFooterView();
    }

    private List<SearchHistoryDataBean> findAllHistorySearch() {
        return mDao.queryBuilder()
                .orderDesc(SearchHistoryDataBeanDao.Properties.SearchTime)
                .list();
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
        }
    }

    @Override
    public void searchGoodsSuccess(HomeGoodsInfo homeGoodsInfo) {
        setData(mPageIndex, homeGoodsInfo.getList());
        mAdapter.notifyDataSetChanged();
    }


    private void setData(int pageIndex, List data) {
        final int size = data == null ? 0 : data.size();
        if (pageIndex == 1) {
            mAdapter.setNewData(data);
            if (size == 0) {
                mAdapter.setEmptyView(mNotDataView);
            }
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < mPageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(false);
        } else {
            mAdapter.loadMoreComplete();
        }
        homeGoodsInfo = mAdapter.getData();
    }

    @Override
    public void showError(String msg) {

    }


}
